/******************************************************************************
 * Copyright (C) 2009 Peter ZHOU <peterzhoulei@gmail.com>                     *
 *                                                                            *
 * This program is free software; you can redistribute it and/or              *
 * modify it under the terms of the GNU General Public License as             *
 * published by the Free Software Foundation; either version 2 of             *
 * the License, or (at your option) any later version.                        *
 *                                                                            *
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU General Public License for more details.                               *
 *                                                                            *
 * You should have received a copy of the GNU General Public License          *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
 ******************************************************************************/

#import "ddIM_dict.h"

@implementation ddIM_dict

-(void)readPreferences
{
	NSLog(@"Reading preferences file...");
	extern bool eneng;
	extern bool ining;
	extern NSString* account;
	extern NSString* password;
	NSDictionary* prefs;
	NSString *filePath  = [[NSBundle mainBundle] pathForResource:@"preferences" ofType:@"plist"];
	prefs = [NSDictionary dictionaryWithContentsOfFile:filePath];
	account = [NSString stringWithString:[prefs objectForKey:@"account"]];
	password = [NSString stringWithString:[prefs objectForKey:@"password"]];
	eneng = [prefs objectForKey:@"eneng"];
	ining = [prefs objectForKey:@"ining"];
}

-(void)readDictFile
{
	NSLog(@"Reading dictionary file...");
	NSString *filePath  = [[NSBundle mainBundle] pathForResource:@"py" ofType:@"txt"];
	NSLog(filePath);
	//TODO: existance check
	[dicFile appendString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]];
	NSMutableArray* arr = [dicFile componentsSeparatedByString:@"\n"];
	version = [NSDate dateWithString:[arr objectAtIndex:0]];
	[arr removeObjectAtIndex:0];
	NSArray* word;
	NSArray* py;
	NSString* wordstr;
	NSInteger freq;
	wordTree = [[ddIM_tree alloc] init];
	NSMutableArray* preWords;
	for ( NSString* str in arr )
	{
		word = [str componentsSeparatedByString:@" "];
		//py word freq
		py = [[word objectAtIndex:0] componentsSeparatedByString:@"'"];
		wordstr = [word objectAtIndex:1];
		freq = [[word objectAtIndex:2] integerValue];
		if ( [word count] > 3 )
		{
			if ( preWords != nil )
				[preWords release];
			preWords = [NSMutableArray arrayWithArray:[word subarrayWithRange:NSMakeRange(3, [word count] - 3)]];
			[wordTree insertWord:py:wordstr:freq:preWords];
		}
		else
			[wordTree insertWord:py:wordstr:freq:nil];
	}
}

-(void)dictionaryUpdated
{
	NSNotificationCenter* nCenter = [NSNotificationCenter defaultCenter];
	NSMutableDictionary* info = [[NSMutableDictionary alloc] init];
	[info setValue:version forKey:@"dicVersion"];
	[nCenter postNotificationName:@"DictionaryChanged" object:self userInfo:info];
}

-(NSArray*)searchDict:(NSString*)py:(NSString*)preWord
{
	NSArray* pyArray;
	NSMutableArray* phrases = [[NSMutableArray alloc] init];
	pyArray = [py componentsSeparatedByString:@"'"];
	if ( [py hasSuffix:@"'"] )
		pyArray = [pyArray subarrayWithRange:NSMakeRange(0, [pyArray count] - 1)];
	if ( [wordTree searchTree:pyArray:preWord] )
	{
		[phrases addObjectsFromArray:[wordTree candidatesPhases]];
		return phrases;
	}
	else
		return nil;
}

-(BOOL)editDict:(NSString*)py:(NSString*)word
{
	NSInteger startLocation;
	NSInteger endLocation;
	NSString* tmpstr = [[[py stringByAppendingString:@" "] stringByAppendingString:word] stringByAppendingString:@" "];
	NSScanner* scanner = [NSScanner scannerWithString:dicFile];
	[scanner scanUpToString:tmpstr intoString:NULL];
	[scanner scanString:tmpstr intoString:NULL];
	startLocation = [scanner scanLocation];
	[scanner scanInt:NULL];
	endLocation = [scanner scanLocation];

	NSString *filePath = [[NSBundle mainBundle] pathForResource:@"py" ofType:@"txt"];
	NSArray* pyArray = [py componentsSeparatedByString:@"'"];
	NSInteger freq = [wordTree editFreq:pyArray:word:nil];
	NSLog([NSString stringWithFormat:@"%d", freq]);
	[dicFile replaceCharactersInRange:NSMakeRange(startLocation, endLocation - startLocation ) withString:[NSString stringWithFormat:@"%d", freq]];
	NSLog([@"editing freq..." stringByAppendingString:word]);
	version = [NSDate date];
	[self dictionaryUpdated];
	[dicFile replaceCharactersInRange:NSMakeRange(0, 25) withString:[version description]];
	[dicFile writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
	return true;
}

-(BOOL)addDict:(NSString*)py:(NSString*)word
{
	NSString* tmpstr = [[py stringByAppendingString:@" "] stringByAppendingString:word];
	NSScanner* scanner = [NSScanner scannerWithString:dicFile];
	[scanner scanUpToString:tmpstr intoString:NULL];
	if ( ![scanner scanString:tmpstr intoString:NULL] )
	{
		NSString* str;
		NSString *filePath = [[NSBundle mainBundle] pathForResource:@"py" ofType:@"txt"];
		NSArray* pyArray = [py componentsSeparatedByString:@"'"];
		str = [[[[py stringByAppendingString:@" "] stringByAppendingString:word] stringByAppendingString:@" "] stringByAppendingString:@"100"];
		[dicFile appendString:@"\n"];
		[dicFile appendString:str];
		NSLog([@"inserting new words..." stringByAppendingString:word]);
		[wordTree insertWord:pyArray:word:0];
		version = [NSDate date];
		[self dictionaryUpdated];
		[dicFile replaceCharactersInRange:NSMakeRange(0, 25) withString:[version description]];
		[dicFile writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
		return true;
	}
	else
	{
		return false;
	}
}

-(BOOL)isCandidate:(NSString*)py
{
	if ( [[wordTree candidatesPY] indexOfObject:py] == NSNotFound )
		return false;
	else
	{
		NSLog(@"candidate found");
		return true;
	}
}

-(NSArray*)candidatesPY
{
	return [wordTree candidatesPY];
}

-(NSDate*)version
{
	return version;
}

-(void)setVersion:(NSDate*)value
{
	[value retain];
	[version release];
	version = value;
}

-(id)init
{
	self = [super init];
	dicFile = [[NSMutableString alloc] init];
	return self;
}

-(void)dealloc
{
	[wordTree release];
	[super dealloc];
}

@end
